package top.ljjapp.security.core.validate.code;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import top.ljjapp.security.core.properties.SecurityProperties;
import top.ljjapp.security.core.validate.code.image.ImageCode;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 验证码验证
 * OncePerRequestFilter保证过滤器只被调用一次
 * InitializingBean其他接口组装完毕后能初始化值
 */
public class ValidateCodeFIlter extends OncePerRequestFilter implements InitializingBean {

    /**
     * 失败处理器
     */
    private AuthenticationFailureHandler authenticationFailureHandler;

    /**
     * session管理器
     */
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();


    /**
     * 多个url
     */
    private Set<String> urls = new HashSet<>();

    /**
     * security自定义的配置
     */
    private SecurityProperties securityProperties;

    /**
     * spring的路径匹配类
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 存放所有需要校验验证码的url
     */
    private Map<String, ValidateCodeType> urlMap = new HashMap<>();

    /**
     * 装载完后配置url
     * @throws ServletException
     */
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        //配置需要验证码的url
        String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(securityProperties.getCode().getImage().getUrl(), ",");
        for (String configUrl: configUrls) {
            urls.add(configUrl);
        }
        urls.add("/authentication/form");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        boolean action = false;
        //验证路径是否匹配
        for (String url: urls) {
            if (pathMatcher.match(url, httpServletRequest.getRequestURI())) {
                action = true;
            }
        }
        //判断表单来的数据是否符合要求
        if (action) {
            try {
                validate(new ServletWebRequest(httpServletRequest));
            } catch (ValidateCodeException e){
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return;
            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    /**
     * 验证码验证
     * @param request
     * @throws ServletRequestBindingException
     */
    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
        ImageCode codeInsession  = (ImageCode) sessionStrategy.getAttribute(request, "SESSION_KEY_FOR_CODE_");
        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "imageCode");

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }

        if (codeInsession == null) {
            throw new ValidateCodeException("验证码不存在");
        }

        if (codeInsession.isExpried()){
            sessionStrategy.removeAttribute(request, "SESSION_KEY_FOR_CODE_");
            throw new ValidateCodeException("验证码过期");
        }

        if (!StringUtils.equals(codeInsession.getCode(), codeInRequest)) {
            throw  new ValidateCodeException("验证码不匹配");
        }

        sessionStrategy.removeAttribute(request, "SESSION_KEY_FOR_CODE_");
    }

    public AuthenticationFailureHandler getAuthenticationFailureHandler() {
        return authenticationFailureHandler;
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    public SessionStrategy getSessionStrategy() {
        return sessionStrategy;
    }

    public void setSessionStrategy(SessionStrategy sessionStrategy) {
        this.sessionStrategy = sessionStrategy;
    }

    public Set<String> getUrls() {
        return urls;
    }

    public void setUrls(Set<String> urls) {
        this.urls = urls;
    }

    public SecurityProperties getSecurityProperties() {
        return securityProperties;
    }

    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }
}
